<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin-top: 16px; margin-bottom: -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <EditDropDown dropdownTitle="入库基本信息">
        <template v-slot:content>
          <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
            <px-row>
              <px-col :span="8">
                <px-form-item label="入库单号" prop="inNum">
                  <px-input v-model="formValue.inNum" placeholder="请输入入库单号" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="入库人" prop="inboundName">
                  <px-input v-model="formValue.inboundName" placeholder="请输入入库人" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col v-if="props.drawerType === 'edit'" :span="8">
                <px-form-item label="修改人">
                  <px-input v-model="editUser" placeholder="请输入修改人" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="种类" prop="category">
                  <px-select v-model="formValue.category" placeholder="请选择种类" filterable clearable @change="categoryChange">
                    <px-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="入库时间" prop="inDate">
                  <px-date-picker
                    v-model="formValue.inDate"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择入库时间"
                    clearable
                    :disabled-date="disabledDate"
                  />
                  <!-- :disabled-hours="disabledHours"
                    :disabled-minutes="disabledMinutes"
                    :disabled-seconds="disabledSeconds" -->
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="8">
                <px-form-item label="来源" prop="source">
                  <px-select v-model="formValue.source" placeholder="请选择来源" filterable clearable>
                    <px-option v-for="item in sourceList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="PO单号" prop="billNum">
                  <px-input v-model="formValue.billNum" placeholder="请输入PO单号" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="备注" prop="remark">
                  <px-input v-model="formValue.remark" placeholder="请输入备注" maxlength="1000" clearable />
                </px-form-item>
              </px-col>
            </px-row>
          </px-form>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="备件列表">
        <template v-slot:content>
          <div style="display: flex">
            <px-button style="margin-bottom: 8px" type="primary" @click="dialogVisible = true">选择备件</px-button>
            <px-button style="margin-right: 8px" type="primary" plain @click="templateDownload">下载模板</px-button>
            <BatchUpload url="/ifp/digitaltwins/api/v1/sparePartNew/inOutImportData" @updateUploadPage="addTableRow" />
          </div>
          <px-table :data="formValue.tableData" class="equip-table" size="small" height="280" border>
            <px-table-column
              v-for="(item, index) in tableColumns"
              :key="index"
              :label="item.label"
              :min-width="item.minWidth"
              :align="item.align"
              :show-overflow-tooltip="item.showOverflowTooltip"
              :fixed="item.fixed"
            >
              <template #default="scope">{{
                scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
              }}</template>
            </px-table-column>
            <px-table-column prop="quantity" label="入库数量" min-width="160" show-overflow-tooltip>
              <template #header>
                入库数量
                <px-icon style="cursor: pointer" @click="editQuantity">
                  <EditPen />
                </px-icon>
              </template>
              <template #default="scope">
                <div v-if="isQuantity">
                  {{ scope.row.quantity }}
                </div>
                <px-input-number v-else v-model="scope.row.quantity" :min="1" size="small" />
              </template>
            </px-table-column>
            <px-table-column fixed="right" label="操作" min-width="144" align="center">
              <template #default="scope">
                <px-tooltip content="删除" placement="top">
                  <px-button link type="danger" icon="Delete" @click="handleDelete(scope.$index)" />
                </px-tooltip>
              </template>
            </px-table-column>
          </px-table>
        </template>
      </EditDropDown>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
  <!-- 选择备件弹窗 -->
  <AddSparePartsDialog :params="sparePartsPrams" :visible="dialogVisible" @closeDialog="closeDialog" @addTableRow="addTableRow" />
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import {
  addSparePartsWarehousing,
  editSparePartsWarehousing,
  getSparePartsWarehousing,
  querySparePartsLedgerNew,
  querySparePartsWarehousingNum
} from "@/api/equip/spareParts";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import BatchUpload from "./BatchUpload.vue";
import dayjs from "dayjs";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watch, getCurrentInstance } from "vue";
import { useRoute } from "vue-router";
import AddSparePartsDialog from "./AddSparePartsDialog.vue";
const { proxy }: any = getCurrentInstance();

const route = useRoute();
// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "sparePartsId"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 备件弹窗参数
const sparePartsPrams = computed(() => {
  const { className, category } = formValue.value;
  const params = {
    className: className,
    category: category
  };
  return params;
});
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    id: "",
    inNum: "",
    inboundName: "",
    inDate: "",
    className: "",
    systemVal: "",
    source: "",
    billNum: "",
    remark: "",
    tableData: []
  },
  tableColumns: [
    { prop: "categoryDesc", label: "种类", minWidth: "140", showOverflowTooltip: true, fixed: "left" },
    { prop: "sparePartCode", label: "编码", minWidth: "140", showOverflowTooltip: true },
    { prop: "sparePartName", label: "名称", minWidth: "140", showOverflowTooltip: true },
    { prop: "typeName", label: "类型", minWidth: "120", showOverflowTooltip: true },
    { prop: "brandName", label: "品牌", minWidth: "120", showOverflowTooltip: true },
    { prop: "supplyModel", label: "厂商型号", minWidth: "120", showOverflowTooltip: true },
    { prop: "model", label: "厂内型号", minWidth: "120", showOverflowTooltip: true },
    { prop: "warehousePositionDesc", label: "库位", minWidth: "120", showOverflowTooltip: true }
  ],
  sourceList: [],
  categoryList: [],
  isQuantity: true,
  dialogVisible: false,
  editUser: ""
});
const { formValue, sourceList, tableColumns, isQuantity, categoryList, dialogVisible, editUser } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  inNum: [{ required: true, message: "入库单号不能为空", trigger: "blur" }],
  inboundName: [{ required: true, message: "入库人不能为空", trigger: "blur" }],
  category: [{ required: true, message: "种类不能为空", trigger: "change" }],
  inDate: [{ required: true, message: "入库时间不能为空", trigger: "blur" }],
  source: [{ required: true, message: "来源不能为空", trigger: "change" }],
  billNum: [{ required: true, message: "PO单号不能为空", trigger: "blur" }]
}));
// 禁用日期
const disabledDate = (time: Date) => {
  return time.getTime() < new Date().getTime() - 8.64e7;
};
// 禁用时
const disabledHours = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.inDate.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 24; i++) {
      if (new Date().getHours() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 禁用分
const disabledMinutes = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.inDate.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 60; i++) {
      if (new Date().getMinutes() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 禁用秒
const disabledSeconds = () => {
  const todayDate = new Date().setHours(0, 0, 0, 0);
  const selectDate = new Date(formValue.value.inDate.slice(0, 10)).setHours(0, 0, 0, 0);
  const arrs = [];
  if (selectDate <= todayDate) {
    for (let i = 0; i < 60; i++) {
      if (new Date().getSeconds() <= i) continue;
      arrs.push(i);
    }
  }
  return arrs;
};
// 种类
const categoryChange = () => {
  formValue.value.tableData = [];
};
// 种类下拉框
const queryCategory = async () => {
  categoryList.value = [];
  const params = {
    typeCode: "typeCategory"
  };
  const data = await queryDictData(params);
  categoryList.value = data;
};
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value.resetFields();
    querySourceList();
    queryCategory();
    isQuantity.value = true;
    if (props.drawerType === "ledger") {
      const sparesList = await querySparePartsLedgerNew({
        pageNum: 1,
        pageSize: 20,
        spareNameOrCode: props.sparePartsId,
        stockAlarm: false
      });
      const spareData = sparesList?.data[0] || {};
      const { className, systemVal, category } = spareData;
      const inNum = await querySparePartsWarehousingNum({});
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      formValue.value = {
        ...formValue.value,
        inNum,
        className,
        systemVal,
        category,
        inDate: dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss"),
        inboundName: userInfo.username + "-" + userInfo.realName,
        tableData: [sparesList?.data[0]]
      };
    } else if (props.drawerType === "add") {
      const data = await querySparePartsWarehousingNum({});
      formValue.value.inNum = data;
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      formValue.value.inboundName = userInfo.username + "-" + userInfo.realName;
      formValue.value.inDate = "";
      formValue.value.className = "";
      formValue.value.systemVal = "";
      formValue.value.source = "";
      formValue.value.billNum = "";
      formValue.value.remark = "";
      formValue.value.tableData = [];
      delete formValue.value.id;
    } else if (props.drawerType === "edit") {
      getDetail();
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      editUser.value = userInfo.username + "-" + userInfo.realName;
    }
  } else {
    formValue.value = {
      id: "",
      inNum: "",
      inboundName: "",
      inDate: "",
      className: "",
      systemVal: "",
      source: "",
      billNum: "",
      remark: "",
      tableData: []
    };
  }
});
// 来源下拉框
const querySourceList = async () => {
  sourceList.value = [];
  const params = {
    typeCode: "source"
  };
  const data = await queryDictData(params);
  sourceList.value = data;
};
// 获取详情接口
const getDetail = async () => {
  const params = {
    id: props.sparePartsId
  };
  const data: any = await getSparePartsWarehousing(params);
  formValue.value.id = data.id;
  formValue.value.inNum = data.inNum;
  formValue.value.inboundName = data.inboundName;
  formValue.value.inDate = data.inDate;
  formValue.value.className = data.className;
  formValue.value.systemVal = data.systemVal;
  formValue.value.source = data.source;
  formValue.value.billNum = data.billNum;
  formValue.value.remark = data.remark;
  formValue.value.category = data.category;
  formValue.value.tableData = data.inventoryDetailDTOList;
};
// 编辑数量
const editQuantity = () => {
  isQuantity.value = !isQuantity.value;
};
// 删除表格某一行
const handleDelete = (index: any) => {
  formValue.value.tableData.splice(index, 1);
};
// 返回主页面
const backMainPage = () => {
  formRef.value.resetFields();
  emits("backMainPage");
};
// 关闭子级dialog弹窗
const closeDialog = () => {
  dialogVisible.value = false;
};
// 选择备件后添加表格数据
const addTableRow = val => {
  if (val && val.length > 0) {
    const arr = [];
    formValue.value.tableData.forEach(item => {
      arr.push(item.id);
    });
    const arr2 = [];
    val.forEach(item => {
      if (!arr.includes(item.id)) {
        arr2.push(item);
      }
    });
    formValue.value.tableData = [...arr2, ...formValue.value.tableData];
  }
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const { tableData, ...rest } = formValue.value;
      if (tableData && tableData.length > 0) {
        const arr = [];
        tableData.forEach(item => {
          arr.push({
            parePartId: item.id,
            quantity: item.quantity
          });
        });
        if (arr && arr.length > 0) {
          const flag = arr.every(item => {
            return item.quantity !== "" && item.quantity !== null;
          });
          if (!flag) {
            PxMessage.error("您尚有未填写的入库数量，请填写完成后进行提交！");
            return;
          }
        }
        const params = { ...rest, inventoryDetailList: arr };
        if (props.drawerType === "add" || props.drawerType === "ledger") {
          await addSparePartsWarehousing(params);
          PxMessage.success("创建成功");
          emits("backMainPage");
          emits("queryTable");
        } else if (props.drawerType === "edit") {
          await editSparePartsWarehousing(params);
          PxMessage.success("编辑成功");
          emits("backMainPage");
          emits("queryTable");
        }
      } else {
        PxMessage.error("备件列表不能为空");
      }
    }
  });
};
// 下载模版
const templateDownload = async () => {
  proxy.download("get", "/digitaltwins/api/v1/sparePartNew/inOutTemplateDownLoad", {}, "备件出入库数据模板.xlsx");
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  if (!isOnlyClass) {
    formRef.value?.resetFields(["systemVal"]);
    formValue.value.tableData = [];
  }
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
